package com.mrjy.queries.bo;

import java.io.File;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.solr.common.SolrInputDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mrjy.common.dto.MyMessagesDto;
import com.mrjy.common.dto.QuestionCommentDto;
import com.mrjy.common.entity.HappinessInfo;
import com.mrjy.common.entity.IntegralInfo;
import com.mrjy.common.entity.MessageInfo;
import com.mrjy.common.entity.QuestionComment;
import com.mrjy.common.entity.QuestionInfo;
import com.mrjy.common.entity.RecordIncomeInfo;
import com.mrjy.common.entity.RecordInfo;
import com.mrjy.common.entity.SolrEntity;
import com.mrjy.common.entity.TeacherInfo;
import com.mrjy.common.entity.UserBalancePayment;
import com.mrjy.common.entity.UserInfo;
import com.mrjy.common.entity.UserMemberInfo;
import com.mrjy.common.enums.ResultEnum;
import com.mrjy.common.solr.SolrServerClient;
import com.mrjy.common.util.ConstantsUtil;
import com.mrjy.common.util.ConvertVoiceUtil;
import com.mrjy.common.util.DateUtil;
import com.mrjy.common.util.ExcelUtil;
import com.mrjy.common.util.GlobalConstant;
import com.mrjy.common.util.ResponseCode;
import com.mrjy.common.util.ResultUtil;
import com.mrjy.integral.dao.IHappinessInfoDao;
import com.mrjy.integral.dao.IIntegralInfoDao;
import com.mrjy.integral.util.HappinessInfoEnum;
import com.mrjy.integral.util.HappinessInfoUtil;
import com.mrjy.integral.util.IntegralEnum;
import com.mrjy.integral.util.IntegralUtil;
import com.mrjy.maintain.bo.IPromoteDetailBo;
import com.mrjy.maintain.dao.IMessageInfoDao;
import com.mrjy.maintain.dao.IRecordIncomeInfoDao;
import com.mrjy.maintain.dao.IRecordInfoDao;
import com.mrjy.maintain.dao.ITeacherInfoDao;
import com.mrjy.maintain.dao.IUserInfoDao;
import com.mrjy.maintain.dao.IUserMemberInfoDao;
import com.mrjy.maintain.dao.IUserSchoolRelDao;
import com.mrjy.maintain.dto.PromoteDetailDTO;
import com.mrjy.payment.dao.IUserBalancePaymentDao;
import com.mrjy.queries.dao.IQuestionCommentDao;
import com.mrjy.queries.dao.IQuestionInfoDao;
import com.mrjy.queries.dao.IQuestionTypeRelDao;
import com.mrjy.queries.dto.NewCommentWithTypesDTO;
import com.mrjy.queries.dto.PayQuestionCommentDTO;
import com.mrjy.queries.dto.PayQuestionCommentParamDTO;
import com.mrjy.queries.util.MyMessagesDtoComparator;
import com.mrjy.share.dto.DistributorInfoDTO;
import com.mrjy.video.dao.IVideoTypeDao;
import com.mrjy.wechat.bo.IWeChatFileUploadBo;
import com.mrjy.wechat.conts.WxConsts;
import com.mrjy.wechat.dto.TemplateMessage;
import com.mrjy.wechat.util.WeChatUtil;

@Service("QuestionCommentBo")
public class QuestionCommentBo implements IQuestionCommentBo {

    @Resource
    private IQuestionCommentDao questionCommentDao;
    @Resource
    private IQuestionInfoDao questionInfoDao;
    @Resource
	private IMessageInfoDao messageInfoDao;
    @Resource
    private IUserInfoDao userDao;
    @Resource
    private IRecordIncomeInfoDao recordIncomeInfoDao;
    @Resource
    private IUserBalancePaymentDao userBalancePaymentDao;
    @Resource
    private IRecordInfoDao recordInfoDao;
    @Resource
    private IWeChatFileUploadBo weChatFileUploadNo;
    @Resource
    private IPromoteDetailBo promoteDetailBo;
    @Resource
	private IUserMemberInfoDao userMemberInfoDao;
    @Resource
	private IIntegralInfoDao integralInfoDao;
    @Resource
	private IHappinessInfoDao happinessInfoDao;
    @Resource
	private SolrServerClient solrServerClient;
    @Resource
	private IUserInfoDao userInfoDao;
    @Resource
	private IUserSchoolRelDao userSchoolRelDao;
    @Resource
	private ITeacherInfoDao teacherInfoDao;
    @Resource
    private IQuestionTypeRelDao questionTypeRelDao ;
    @Resource
    private IVideoTypeDao videoTypeDao ;

    private Logger LOGGER = LoggerFactory.getLogger(QuestionCommentBo.class);

    @Override
    public List<QuestionComment> queryComments(QuestionComment comment, UserInfo userInfo) {
        if (userInfo == null) {
            return new ArrayList<QuestionComment>();
        }
        if (comment.getQuestionId() == null) {
            return new ArrayList<QuestionComment>();
        }
        List<QuestionComment> comments = questionCommentDao.queryCommentsByPage(comment);
        return comments;
    }

    @Override
    public String doComment(QuestionComment comment, UserInfo userInfo) {
        if (userInfo == null) {
            return "userInfo_error";
        }
        if (comment.getQuestionId() == null && StringUtils.isBlank(comment.getCommentContent())) {
            return "error";
        }
        QuestionInfo q = new QuestionInfo();
        q.setId(comment.getQuestionId());
        QuestionInfo existQuestion = questionInfoDao.queryById(q);
        if (existQuestion == null) {
            return "error";
        }
        comment.setUserId(userInfo.getId());
        comment.setCommentTime(new Date());

        if (comment.getQuoteCommentId() == null) {
            comment.setCommentedId(existQuestion.getUserId());
            questionCommentDao.insert(comment);
            questionInfoDao.addCommentNum(comment.getQuestionId());
            return "ok";
        } else {
        	QuestionComment voComment = new QuestionComment();
        	voComment.setId(comment.getQuoteCommentId());
        	voComment.setDisableFlag(0);
            QuestionComment qc = questionCommentDao.queryById(comment);
            if (qc != null && qc.getQuestionId().intValue() == comment.getQuestionId().intValue()) {
                comment.setCommentedId(qc.getUserId());
                questionCommentDao.insert(comment);
                questionInfoDao.addCommentNum(comment.getQuestionId());
                return "ok";
            } else {
                return "error";
            }
        }

    }

    @Override
    public Object queryCommentListByUserId(QuestionInfo info) {
        Map<String, Object> map = new HashMap<String, Object>();
        if (null == info) {
            map.put("err_code", -1);
            map.put("err_msg", "userId为空");
            map.put("total", 0);
            map.put("rows", null);
        }
        int total = questionInfoDao.queryTotalCommentCountByUserId(info.getUserId());
        if (total > 0) {
            List<QuestionInfo> list = questionInfoDao.queryCommentListByUserId(info);
            if (null != list && list.size() > 0) {
                map.put("err_code", 0);
                map.put("err_msg", "查询成功");
                map.put("total", total);
                map.put("rows", list);
            }
        } else {
            map.put("err_code", 2);
            map.put("err_msg", "无数据");
            map.put("total", 0);
            map.put("rows", null);
        }
        return map;
    }

    @Override
    public Object selectCommentByQuestionId(QuestionComment info) {
        Map<String, Object> map = new HashMap<String, Object>();
        if (null == info.getQuestionId()) {
            map.put("err_code", -1);
            map.put("err_msg", "questionId为空");
            map.put("total", 0);
            map.put("rows", null);
        }
        int total = questionCommentDao.queryTotalFirstCommentCountByQuestionId(info.getQuestionId());
        if (total > 0) {
            List<QuestionComment> list = questionCommentDao.selectCommentByQuestionId(info);
            if (null != list && list.size() > 0) {
                List<QuestionComment> resultList = new ArrayList<QuestionComment>();
                for (QuestionComment comment : list) {
                    if (comment.getCommentTime() != null) {
                        long now = new Date().getTime();
                        long qt = 0;//时间差
                        qt = (now - comment.getCommentTime().getTime()) / 1000;
                        if (qt < 60) {
                            comment.setCommentTimeString("刚刚");
                        } else if ((qt /= 60) < 60) {
                            comment.setCommentTimeString(qt + "分钟前");
                        } else if ((qt /= 60) < 24) {
                            comment.setCommentTimeString(qt + "小时前");
                        } else if ((qt /= 24) < 5) {
                            comment.setCommentTimeString(qt + "天前");
                        } else {
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
                            comment.setCommentTimeString(sdf.format(comment.getCommentTime()));
                        }
                    }
                    resultList.add(comment);
                }
                map.put("err_code", 0);
                map.put("err_msg", "查询成功");
                map.put("total", total);
                map.put("rows", resultList);
            }
        } else {
            map.put("err_code", 2);
            map.put("err_msg", "无数据");
            map.put("total", 0);
            map.put("rows", null);
        }
        return map;
    }

    @Override
    public Object queryPageCommentsOrderByNum(QuestionComment comment) {
        Map<String, Object> map = new HashMap<String, Object>();
        
        int total = questionCommentDao.countCommentsOrderByNum(comment);
        map.put("total", total);
        if(total > 0){
        	List<QuestionComment> list = questionCommentDao.queryPageCommentsOrderByNum(comment);
            for (QuestionComment questionComment : list) {
                String format = DateUtil.dateFormat(questionComment.getCommentTime());
                questionComment.setCommentTimeString(format);
            }
            
            if (null != list && list.size() > 0) {
                map.put("err_code", 0);
                map.put("err_msg", "查询成功");
                map.put("rows", list);
            } else {
                map.put("err_code", 2);
                map.put("err_msg", "无数据");
                map.put("rows", null);
            }
        }
        return map;
    }

    @Override
    public Object queryPageCommentsHot(QuestionComment comment, HttpSession session) {
        Map<String, Object> map = new HashMap<String, Object>();
        //get userId
        UserInfo userInfo = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
//        if (userInfo == null) {
//            map.put("err_code", -1);
//            map.put("err_msg", "当前用户未登录");
//            return map;
//        }
//        Integer id = userInfo.getId();
        comment.setGoodUserId(userInfo==null?null:userInfo.getId());
        UserMemberInfo userMemberInfo = userMemberInfoDao.selectIsVipByUserId(userInfo==null?null:userInfo.getId());

        List<QuestionComment> list1 = questionCommentDao.queryPageCommentsHot(comment);

        ListIterator<QuestionComment> questionCommentListIterator = list1.listIterator();
        while (questionCommentListIterator.hasNext()) {
            QuestionComment next = questionCommentListIterator.next();
            Integer isNeedPrivilege = next.getIsNeedPrivilege();
            if (isNeedPrivilege != null && isNeedPrivilege.equals(1)) {
                //付费提问
                if (next.getTimeOut() == 0) {
                    //免费三小时
                    next.setStatus(0);
                } else if ((comment.getGoodUserId() != null) && (comment.getGoodUserId().equals(next.getUserId()) || comment.getGoodUserId().equals(next.getCommentedId()))) {
                    next.setStatus(1);//导师判断,回答人和当前用户一直就是受益人
                } else if (null != userMemberInfo) {//会员
                    //用户可以直接收听语音，返回权限通过
                    next.setStatus(4);
                } else if (next.getUbpId() != null) {
                    //用户可以直接收听语音，返回权限通过
                    next.setStatus(2);
                } else {
                    //订单没有支付
                    next.setStatus(3);
                }
            }
        }
        if (null != list1 && list1.size() > 0) {
            map.put("err_code", 0);
            map.put("err_msg", "查询成功");
            map.put("rows", list1);
        } else {
            map.put("err_code", 2);
            map.put("err_msg", "无数据");
            map.put("rows", null);
        }
        return map;
    }

    @Override
    public Object txToComment(QuestionComment qComment, RecordInfo recordInfo) {
        QuestionInfo existQuestion;
        Map<String, Object> map = new HashMap<String, Object>();
        if (null == qComment) {
            map.put("err_code", -1);
            map.put("err_msg", "传进来的对象为空");
            return map;
        }
        if (qComment.getUserId() == 0) {
            map.put("err_code", -2);
            map.put("err_msg", "评论人id为空");
            return map;
        }
        if (qComment.getQuestionId() == 0) {
            map.put("err_code", -2);
            map.put("err_msg", "问题id为空");
            return map;
        } else {
            QuestionInfo q = new QuestionInfo();
            q.setId(qComment.getQuestionId());
            q.setDisableFlag(0);
            existQuestion = questionInfoDao.queryById(q);
            if (existQuestion == null) {
                map.put("err_code", -3);
                map.put("err_msg", "通过questionId查无此记录");
                return map;
            }

            map.put("openid", existQuestion.getWeixinOpenid());
            map.put("commentNum", existQuestion.getCommentNum());
        }

        //判断用户是否已经对该问题进行过评论了，回复可以多个,防止单个用户多次评论
        //1.6.9.2 现一个用户可以对一个帖子进行多次跟帖
//        if (qComment.getQuoteCommentId() == null) {
//            QuestionComment questionComment = questionCommentDao.queryCommentByQid(qComment);
//            if (questionComment != null) {
//                map.put("err_code", -4);
//                map.put("err_msg", "你已经对该问题进行过评论");
//                return map;
//            }
//        }

        qComment.setReadFlag(0);
        qComment.setCommentTime(new Date());
        qComment.setDisableFlag(0);
        qComment.setGoodNum(0);
        qComment.setCommentNum(0);
        if (recordInfo.getRecordCode() != null) {
            qComment.setIsNeedPrivilege(1);

            HashMap mediaMap = new HashMap<>();
            mediaMap.put("mediaId", recordInfo.getRecordCode());
            Map<String, Object> resultMap = weChatFileUploadNo.uploadWXFile(mediaMap);

            if (!resultMap.get("err_code").toString().equals("0")) {
                return resultMap;
            }

            File file = (File) resultMap.get("file");
            String absolutePath = file.getAbsolutePath();
            String targetPath = absolutePath.replace(".amr", ".mp3");

            ConvertVoiceUtil.changeToMp3(absolutePath, targetPath);
            long mp3Duration = ConvertVoiceUtil.getMP3Duration(targetPath);
            File targetFile = new File(targetPath);
            if (!targetFile.exists()) {
                map.put("err_code", -4);
                map.put("err_msg", "语音格式转化失败");
                return map;
            }
            //生成recordinfo对象
            recordInfo.setDuration(Integer.valueOf(mp3Duration + ""));
            recordInfo.setRecordName(targetFile.getName());
            recordInfo.setFileSize(targetFile.length() / 1024);
            recordInfo.setCreateTime(new Timestamp(System.currentTimeMillis()));
            recordInfo.setDisableFlag(0);
            recordInfo.setPlayTimes(0);
            recordInfo.setFreeFlag(1);
        } else if (qComment.getIsNeedPrivilege() != null && qComment.getIsNeedPrivilege().equals(1)) {
            qComment.setDisableFlag(2);//待激活
        } else {
            qComment.setIsNeedPrivilege(0);
        }
        if(qComment.getIsAnonymous() == null){
        	qComment.setIsAnonymous(1);
        }
        int count = questionCommentDao.insert(qComment);
        if (count > 0) {
        	QuestionInfo info = new QuestionInfo();
        	info.setId(qComment.getQuestionId());
        	info.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        	questionInfoDao.updateById(info);
        	questionInfoDao.addCommentNum(qComment.getQuestionId());
        	
        	//向solr库中添加索引 (二级评论不加入索引库)
        	if (qComment.getQuoteCommentId()==null) {
        		try {
	        		SolrEntity entity = new SolrEntity();
	        		if (recordInfo.getRecordCode() != null) {
	        			//语音回答
	        			entity.setRecordName(recordInfo.getRecordName());
	        			entity.setRecordDuration(recordInfo.getDuration()+"");
	        		}else {
	        			//文字回答
	        			entity.setCommentContent(qComment.getCommentContent());
	        		}
            		entity.setId("questionComment_"+qComment.getId());
            		entity.setCommentId(qComment.getId());
            		entity.setQuestionId(qComment.getQuestionId());
            		entity.setQuestionContent(existQuestion.getQuestionContent());
            		UserInfo commentUser = userDao.queryByIdForBack(qComment.getUserId());
            		entity.setUserId(qComment.getUserId());
            		entity.setHeadImgUrl(commentUser.getHeadImgUrl());
            		entity.setPicName(commentUser.getPicName());
            		TeacherInfo ti = teacherInfoDao.queryTeacherByUserId(qComment.getUserId()) ;
            		if(ti == null){
            			entity.setReplyType("0");//用户回答
            		}else{
            			entity.setReplyType("1");//老师回答
            		}
            		String types = questionTypeRelDao.queryTypesByQuestionId(qComment.getQuestionId());
            		entity.setQuestionTypes(types);
            		
            		solrServerClient.add(entity);
            		map.put("solr_msg", "索引插入成功");
            	} catch (Exception e) {
            		e.printStackTrace();
            		LOGGER.debug("[索引插入失败]："+e.getMessage());
            		map.put("solr_msg", "索引插入失败");
            		map.put("err_code", 1);
            		map.put("err_msg", "评论不成功");
            		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            		return map;
            	}
			}

            //导师付费回答
            if (qComment.getIsNeedPrivilege().equals(1)) {
                //查询问题付款情况
                UserBalancePayment userBalancePayment = new UserBalancePayment();
                userBalancePayment.setPaymentProgramId(qComment.getQuestionId());
                userBalancePayment.setUserId(qComment.getCommentedId());//付款人是提问人
                userBalancePayment.setTypeId(8);//付费提问
                UserBalancePayment userBalancePayment1 = userBalancePaymentDao.queryRecordHadPayment(userBalancePayment);//必须得找到
                if (userBalancePayment1 == null) {
                    map.put("err_code", -5);
                    map.put("err_msg", "订单查询失败");
                    return map;
                }

                //导师付费语音回答
                if (recordInfo.getRecordCode() != null) {
                    //插入语音到语音表，改变收益，
                    recordInfo.setCommentId(qComment.getId());
                    int insert = recordInfoDao.insert(recordInfo);
                    if (insert > 0) {
                        //给老师收益
                        RecordIncomeInfo recordIncomeInfo = new RecordIncomeInfo();
                        recordIncomeInfo.setRegisterDate(new Date());
                        recordIncomeInfo.setPaymentId(userBalancePayment1.getId());
                        recordIncomeInfo.setCostName("付费回答");
                        recordIncomeInfo.setCostTypeId(1);
                        recordIncomeInfo.setMoney(BigDecimal.valueOf(userBalancePayment1.getMoney()));
                        recordIncomeInfo.setSettleStatus(1);
                        recordIncomeInfo.setBeneficiaryId(qComment.getUserId());
                        recordIncomeInfoDao.insert(recordIncomeInfo);

                        UserInfo userInfo = userDao.queryById(qComment.getUserId());
                        TemplateMessage message = new TemplateMessage();
                        Map<String, String> dataMap = new HashMap<String, String>();

                        //时间格式话
                        Date currentTime = new Date();
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd日 HH:mm");
                        String dateString = formatter.format(currentTime);
                        //提问用户的openid获得
                        UserInfo userInfo1 = userDao.queryById(existQuestion.getUserId());

                        dataMap.put("first", "你的提问已经被" + userInfo.getUserName() + "回答");
                        dataMap.put("keyword1", existQuestion.getQuestionContent());
                        dataMap.put("keyword2", userInfo.getUserName());
                        dataMap.put("keyword3", dateString);
                        dataMap.put("remark", "快去听听专家怎么说。分享出去，还能获得分成");

                        String url = WxConsts.PUBLIC_DOMAIN + "/index.html?from=weQA/record_anwser.html@_@id=" + existQuestion.getId();
                        message.setDataMap(dataMap);
                        message.setOpenid(userInfo1.getWeixinOpenid());
                        message.setUrl(url);
                        message.setSendType("2");
                        WeChatUtil.sendWechatTemplateMessage(message);
                    } else {
                        map.put("err_code", 1);
                        map.put("err_msg", "语音评论不成功");
                    }
                    //导师文字回答
                } else if (StringUtils.isNotBlank(qComment.getCommentContent())) {
                    //给老师收益
                    RecordIncomeInfo recordIncomeInfo = new RecordIncomeInfo();
                    recordIncomeInfo.setRegisterDate(new Date());
                    recordIncomeInfo.setPaymentId(userBalancePayment1.getId());
                    recordIncomeInfo.setCostName("付费回答");
                    recordIncomeInfo.setCostTypeId(1);
                    recordIncomeInfo.setMoney(BigDecimal.valueOf(userBalancePayment1.getMoney()));
                    recordIncomeInfo.setSettleStatus(1);
                    recordIncomeInfo.setBeneficiaryId(qComment.getUserId());
                    recordIncomeInfoDao.insert(recordIncomeInfo);


                    UserInfo userInfo = userDao.queryById(qComment.getUserId());
                    TemplateMessage message = new TemplateMessage();
                    Map<String, String> dataMap = new HashMap<String, String>();

                    //时间格式话
                    Date currentTime = new Date();
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd日 HH:mm");
                    String dateString = formatter.format(currentTime);
                    //提问用户的openid获得
                    UserInfo userInfo1 = userDao.queryById(existQuestion.getUserId());

                    dataMap.put("first", "你的提问已经被" + userInfo.getUserName() + "回答");
                    dataMap.put("keyword1", existQuestion.getQuestionContent());
                    dataMap.put("keyword2", userInfo.getUserName());
                    dataMap.put("keyword3", dateString);
                    dataMap.put("remark", "快去看看专家怎么说。分享出去，还能获得分成");

                    String url = WxConsts.PUBLIC_DOMAIN + "/index.html?from=weQA/record_anwser.html@_@id=" + existQuestion.getId();
                    message.setDataMap(dataMap);
                    message.setOpenid(userInfo1.getWeixinOpenid());
                    message.setUrl(url);
                    message.setSendType("2");
                    WeChatUtil.sendWechatTemplateMessage(message);

                    qComment.setDisableFlag(0);
                    questionCommentDao.updateById(qComment);
                }
                map.put("err_code", 0);
                map.put("err_msg", "评论成功");
            } else {
                map.put("err_code", 0);
                map.put("err_msg", "评论成功");
            }
            Integer score = addIntegral(qComment);
            map.put("score", score);
        } else {
            map.put("err_code", 1);
            map.put("err_msg", "评论不成功");
        }
        return map;
    }

    @Override
    public Object selectSecondCommentByQuoteCommentId(QuestionComment info) {
        Map<String, Object> map = new HashMap<String, Object>();
        if (null == info.getQuoteCommentId()) {
            map.put("err_code", -1);
            map.put("err_msg", "quoteCommentId为空");
            map.put("rows", null);
            return map;
        }
        List<QuestionComment> list = questionCommentDao.selectSecondCommentByQuoteCommentId(info);
        if (null != list && list.size() > 0) {
            List<QuestionComment> resultList = new ArrayList<QuestionComment>();
            for (QuestionComment comment : list) {
                if (comment.getCommentTime() != null) {
                    long now = new Date().getTime();
                    long qt = 0;//时间差
                    qt = (now - comment.getCommentTime().getTime()) / 1000;
                    if (qt < 60) {
                        comment.setCommentTimeString("刚刚");
                    } else if ((qt /= 60) < 60) {
                        comment.setCommentTimeString(qt + "分钟前");
                    } else if ((qt /= 60) < 24) {
                        comment.setCommentTimeString(qt + "小时前");
                    } else if ((qt /= 24) < 5) {
                        comment.setCommentTimeString(qt + "天前");
                    } else {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
                        comment.setCommentTimeString(sdf.format(comment.getCommentTime()));
                    }
                }
                resultList.add(comment);
            }
            map.put("err_code", 0);
            map.put("err_msg", "查询成功");
            map.put("rows", resultList);
        } else {
            map.put("err_code", 1);
            map.put("err_msg", "无数据");
            map.put("rows", null);
        }
        return map;
    }

    @Override
    public Object queryById(Integer id) {
        Map<String, Object> map = new HashMap<String, Object>();
        if (id == 0) {
            map.put("err_code", -1);
            map.put("err_msg", "id为0");
            return map;
        }
        QuestionComment comment = new QuestionComment();
        comment.setId(id);
        comment = questionCommentDao.queryById(comment);
        if (null != comment) {
        	//根据questionId查询问题的所有一级评论数
        	int commentNumCount = questionCommentDao.queryFirstCommentNumByQuestionId(comment.getQuestionId()) ;
            map.put("err_code", 0);
            map.put("err_msg", "查询成功");
            map.put("questionComment", comment);
            map.put("commentNumCount", commentNumCount) ;
        } else {
            map.put("err_code", 1);
            map.put("err_msg", "无数据");
            map.put("questionComment", comment);
        }
        return map;
    }

    @Override
    public Object queryMyQAPageByUserId(QuestionComment comment, HttpSession session) {
        Map<String, Object> map = new HashMap<String, Object>();

        //get userId
        UserInfo userInfo = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
        UserMemberInfo userMemberInfo = null;
//        if (userInfo == null) {
//            map.put("err_code", -1);
//            map.put("err_msg", "当前用户未登录");
//            return map;
//        } else {
//            Integer id = userInfo.getId();
//            comment.setGoodUserId(id);
//
//            userMemberInfo = userMemberInfoDao.selectIsVipByUserId(userInfo.getId());
//        }
        comment.setGoodUserId(userInfo==null?null:userInfo.getId());
        userMemberInfo = userMemberInfoDao.selectIsVipByUserId(userInfo==null?null:userInfo.getId());
        
        PageHelper.startPage(comment.getPage(), comment.getRows());
        List<QuestionCommentDto> list = questionCommentDao.queryMyQAPageByUserId(comment);
        PageInfo<QuestionCommentDto> pageInfo = new PageInfo<>(list);
        dealListenAuth(comment, list,userMemberInfo);
        if (null != list && list.size() > 0) {
            map.put("err_code", 0);
            map.put("err_msg", "查询成功");
            map.put("rows", list);
        } else {
            map.put("err_code", 1);
            map.put("err_msg", "无数据");
            map.put("rows", null);
        }
        map.put("total", pageInfo.getTotal());
        return map;
    }

    @Override
    public Object queryMyMessagesPageByCommentedId(MyMessagesDto dto) {
        Map<String, Object> map = new HashMap<String, Object>();
        MessageInfo info = new MessageInfo();
        info.setUserId(dto.getCommentedId());
        int totalUnReadCommentNum = questionCommentDao.queryTotalUnReadNumByCommentedId(info);
        int totalUnreadGoodNum = questionCommentDao.queryTotalUnreadGoodNumByCommentedId(info);
        int totalUnreadRecordNum = questionCommentDao.queryTotalUnreadRecordNumByCommentedId(dto.getCommentedId());
        int totalUnReadNum = totalUnReadCommentNum +totalUnreadRecordNum;
        int count =  messageInfoDao.selectNotReadMsgCountByUserId(dto.getCommentedId());
        List<MyMessagesDto> listComment = questionCommentDao.queryMyMessagesCommentPageByCommentedId(dto);
        List<MyMessagesDto> myMessagesDtos = questionCommentDao.queryMyMessagesInvitedPageByCommentedId(dto);

        List<MyMessagesDto> list = new ArrayList<MyMessagesDto>();
        list.addAll(listComment);
        //list.addAll(listGood);
        list.addAll(myMessagesDtos);
        MyMessagesDtoComparator comparator = new MyMessagesDtoComparator();
        Collections.sort(list, comparator);
        map.put("count", count);
        map.put("totalUnReadNum", totalUnReadNum);
        map.put("totalUnreadGoodNum", totalUnreadGoodNum);
        if (null != list && list.size() > 0) {
            map.put("err_code", 0);
            map.put("err_msg", "查询成功");
            map.put("rows", list);

        } else {
            map.put("err_code", 1);
            map.put("err_msg", "无数据");
            map.put("rows", null);
        }
        return map;
    }

    @Override
    public Object txUpdateReadFlagToReaded(Integer id) {
        Map<String, Object> map = new HashMap<String, Object>();
        int count = questionCommentDao.updateReadFlagToReaded(id);
        if (count > 0) {
            map.put("err_code", 0);
            map.put("err_msg", "更新成功");
        } else {
            map.put("err_code", 1);
            map.put("err_msg", "更新失败");
        }
        return map;
    }

    @Override
    public Object queryCommentByQid(QuestionComment comment) {
        Map<String, Object> map = new HashMap<String, Object>();
        if (comment.getUserId() == null) {
            map.put("err_code", -1);
            map.put("err_msg", "用户id为空");
            return map;
        }
        if (comment.getQuestionId() == null) {
            map.put("err_code", -2);
            map.put("err_msg", "问题id为空");
            return map;
        }
        QuestionComment existComment = questionCommentDao.queryCommentByQid(comment);
        if (null == existComment) {
            map.put("err_code", 1);
            map.put("err_msg", "可以回答");
            return map;
        } else {
            map.put("err_code", 0);
            map.put("err_msg", "编辑回答");
            map.put("info", existComment);
            return map;
        }
    }

    @Override
    public Object txUpdateById(QuestionComment comment,HttpSession session) {
        Map<String, Object> map = new HashMap<String, Object>();
        UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
//        if (comment.getUserId() == null) {
//            map.put("err_code", -1);
//            map.put("err_msg", "用户id为空");
//            return map;
//        }
//        if (comment.getQuestionId() == null) {
//            map.put("err_code", -2);
//            map.put("err_msg", "问题id为空");
//            return map;
//        }
        if (comment.getId() == null) {
            map.put("err_code", -3);
            map.put("err_msg", "评论id为空");
            return map;
        }
    /*	try {
            comment.setCommentContent(URLDecoder.decode(comment.getCommentContent(), "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}*/
        comment.setReadFlag(0);
        int result = questionCommentDao.updateById(comment);
        
        if (result == 1) {
        	try {
        		//更新回答索引 
        		SolrInputDocument document = new SolrInputDocument();
        		document.addField("id", "questionComment_"+comment.getId());
        		Map<String, String > operation = new HashMap<>();
        		operation.put("set", comment.getCommentContent());
        		document.addField("commentContent", operation);
        		TeacherInfo ti = teacherInfoDao.queryTeacherByUserId(comment.getUserId()) ;
        		if(ti == null){
        			document.addField("replyType","0");//用户回答
        		}else{
        			document.addField("replyType","1");//老师回答
        		}
        		String types = questionTypeRelDao.queryTypesByQuestionId(comment.getQuestionId());
        		document.addField("questionTypes",types);
        		
        		solrServerClient.addDoc(document);
        		map.put("solr_msg", "索引更新成功");
        	} catch (Exception e) {
        		e.printStackTrace();
        		LOGGER.debug("[索引更新失败]："+e.getMessage());
        		map.put("solr_msg", "索引更新失败");
        		map.put("err_code", 500);
        		map.put("err_msg", "更新回答失败");
        		//事务回滚
        		TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        		return map;
        	}
            map.put("err_code", 200);
            map.put("err_msg", "更新回答成功");
            return map;
        } else {
            map.put("err_code", 500);
            map.put("err_msg", "更新回答失败");
            return map;
        }
    }

    @Override
    public Object txUpdateDisableFlag(QuestionComment comment, UserInfo userInfo) {
    	Map<String, Object> map = new HashMap<String, Object>();
    	if(null == userInfo ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
    	if (comment.getIds()==null||comment.getIds().length==0) {
    		map.put("err_code", 400);
            map.put("err_msg", "请勾选要操作的记录");
            return map;
		}
        int row = questionCommentDao.updateDisableFlag(comment);
        if (row>0) {
        	if (comment.getDisableFlag().intValue() == 0) {
				//数据库启用,添加回答索引
				try {
					//添加提问索引 
					QuestionComment questionComment = null;
					RecordInfo recordInfo = null;
					for (Integer id : comment.getIds()) {
						SolrEntity commentEntity = new SolrEntity();
						questionComment = new QuestionComment();
						questionComment.setId(id);
						questionComment = questionCommentDao.queryById(questionComment);
						//用commentId去语音表查,看是否属于语音回答
	                	recordInfo = recordInfoDao.queryByCommentId(id);
	                	if (recordInfo != null) {
	                		//语音回答
	                		commentEntity.setRecordName(recordInfo.getRecordName());
	                		commentEntity.setRecordDuration(recordInfo.getDuration()+"");
	                	}else {
	                		//文字回答
	                		commentEntity.setCommentContent(questionComment.getCommentContent());
	                	}
	                	commentEntity.setId("questionComment_"+id);
	                	commentEntity.setCommentId(id);
	                	commentEntity.setQuestionId(questionComment.getQuestionId());
	                	commentEntity.setQuestionContent(questionComment.getQuestionContent());
	                	UserInfo commentUser = userInfoDao.queryByIdForBack(questionComment.getUserId());
	                	commentEntity.setUserId(questionComment.getUserId());
	                	commentEntity.setHeadImgUrl(commentUser.getHeadImgUrl());
	                	commentEntity.setPicName(commentUser.getPicName());
	                	TeacherInfo ti = teacherInfoDao.queryTeacherByUserId(questionComment.getUserId()) ;
	            		if(ti == null){
	            			commentEntity.setReplyType("0");//用户回答
	            		}else{
	            			commentEntity.setReplyType("1");//老师回答
	            		}
	            		String types = questionTypeRelDao.queryTypesByQuestionId(questionComment.getQuestionId());
	            		commentEntity.setQuestionTypes(types);;
	                	solrServerClient.add(commentEntity);
					}
					map.put("solr_msg", "索引添加成功");
				} catch (Exception e) {
					e.printStackTrace();
					LOGGER.debug("[索引删除失败]："+e.getMessage());
					map.put("solr_msg", "索引添加失败");
					map.put("err_code", 500);
		            map.put("err_msg", "操作失败");
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return map;
				}
			}else if (comment.getDisableFlag().intValue() == 1) {
				//数据库禁用,要删除索引
				try {
					for (Integer id : comment.getIds()) {
						solrServerClient.deleteById("questionComment_"+id);
					}
					map.put("solr_msg", "索引删除成功");
				} catch (Exception e) {
					e.printStackTrace();
					LOGGER.debug("[索引删除失败]："+e.getMessage());
					map.put("solr_msg", "索引删除失败");
					map.put("err_code", 500);
		            map.put("err_msg", "操作失败");
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					return map;
				}
			}
        	map.put("err_code", 200);
            map.put("err_msg", "操作成功,"+row+"条记录受影响");
		}else {
			map.put("err_code", 500);
            map.put("err_msg", "操作失败,"+row+"条记录受影响");
		}
        return map;
    }

    @Override
    public Object selectQuestionCommentListPage(QuestionComment info,HttpSession session) {
        Map<String, Object> map = new HashMap<String, Object>();
        UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
        if (null == info) {
            map.put("err_code", 400);
            map.put("err_msg", "参数异常");
            return map;
        }
        QuestionComment comment = new QuestionComment();
        int total = questionCommentDao.countQuestionComment(info);
        if (total>0) {
        	List<QuestionComment> list = questionCommentDao.selectQuestionCommentListPage(info);
        	if (null != list && list.size() > 0) {
        		for (QuestionComment questionComment : list) {
        			questionComment.setCommentTimeString(DateUtil.longToString(questionComment.getCommentTime().getTime(), DateUtil.FULL_DATE));
        		}
        		map.put("err_code", 0);
        		map.put("err_msg", "查询成功");
        		map.put("rows", list);
        		map.put("total", total);
                map.put("totalComment", total);
            } else {
        		map.put("err_code", 1);
        		map.put("er_msg", "无数据");
        		map.put("total", total);
        		map.put("rows", list);
                map.put("totalComment", total);
            }
		}else {
			map.put("err_code", 1);
    		map.put("er_msg", "无数据");
    		map.put("total", total);
    		map.put("rows", null);
            map.put("totalComment", total);
        }
        return map;
    }


    @Override
    public Object queryPageCommentWithRecord(QuestionComment info) {
        Map<String, Object> map = new HashMap<String, Object>();
        if (null == info) {
            map.put("err_code", -1);
            map.put("err_msg", "查询出错");
            return map;
        }
        List<QuestionCommentDto> list = questionCommentDao.queryPageCommentWithRecord(info);

        map.put("rows", list);

        return map;
    }

    /**
     * 语音权限查询
     *
     * @param info
     * @return
     */
    @Override
    public Object listenRecord(QuestionComment info) {
        Map<String, Object> map = new HashMap<String, Object>();

        if (info.getUserId() == null || info.getQuestionId() == null) {
            map.put("err_code", -1);
            map.put("err_msg", "参数信息为空");
            return map;
        }
        QuestionComment questionComment = questionCommentDao.queryCommentInfoByQid(info);
        //导师判断,回答人和当前用户一直就是受益人
        if (questionComment.getTimeOut() == 0) {
            //免费三小时
            map.put("err_code", 0);
            map.put("err_msg", "免费时段");
            return map;
        }
        if (questionComment.getUserId().equals(info.getUserId())||questionComment.getCommentedId().equals(info.getUserId())) {
            map.put("err_code", 1);
            map.put("err_msg", "可以偷听");
            return map;
        }
        UserMemberInfo userMemberInfo = userMemberInfoDao.selectIsVipByUserId(info.getUserId());
        if (userMemberInfo != null) {
            map.put("err_code", 4);//会员状态
            map.put("err_msg", "会员免费");
            return map;
        }
        //查询权限(偷听，已经付费),导师（commenterId）是没有的，支付用户和普通用户是这里
        UserBalancePayment userBalancePayment = new UserBalancePayment();
        userBalancePayment.setPaymentProgramId(info.getQuestionId());
        userBalancePayment.setUserId(info.getUserId());
        userBalancePayment.setTypeId(6);//偷听是6
        UserBalancePayment userBalancePayments = userBalancePaymentDao.queryRecordHadPayment(userBalancePayment);
        if (userBalancePayments != null) {
            //用户可以直接收听语音，返回权限通过
            map.put("err_code", 2);
            map.put("err_msg", "可以偷听");
            return map;
        }

        //用户需要购买
        map.put("err_code", 3);
        map.put("err_msg", "不可以偷听");//订单没有支付
        return map;
    }

    @Override
    public Object querySumGoodNumByUserId(QuestionComment info, HttpSession session) {
        Map<String, Object> map = new HashMap<String, Object>();
        RecordIncomeInfo recordIncomeInfo = new RecordIncomeInfo();
        UserInfo ui = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
        if (ui == null) {
            map.put("err_code", ResponseCode.USER_ERROR.getCode());
            map.put("err_msg", ResponseCode.USER_ERROR.getDesc());
            map.put("sumGoodNum", 0);
            map.put("rows", 0);
            map.put("disTotalMoney", 0);
            map.put("totalIntegral", 0);
            return map;
        }

        recordIncomeInfo.setBeneficiaryId(info.getUserId());
        int sumGoodNum = questionCommentDao.querySumGoodNumByUserId(info);
        Map<String, Object> stringObjectMap = recordIncomeInfoDao.queryDetailByBeneficiaryId(recordIncomeInfo);
        PromoteDetailDTO dto = new PromoteDetailDTO();
        dto.setRecommendId(info.getUserId());
        HashMap hashMap = (HashMap) promoteDetailBo.querySumPromoteDetailByUserId(dto, session);
        BigDecimal totalMoney = new BigDecimal(0);
        if (hashMap.get("err_code").equals(0)) {
            DistributorInfoDTO distributorInfoDTO = (DistributorInfoDTO) hashMap.get("info");
            totalMoney = distributorInfoDTO.getTotalMoney() == null ? new BigDecimal(0) : distributorInfoDTO.getTotalMoney();
        }
        //查询总积分
        IntegralInfo integral = new IntegralInfo();
        integral.setUserId(info.getUserId());
        int totalIntegral = (int) integralInfoDao.queryToTalIntegralByUserId(integral);
        
        if (stringObjectMap == null || stringObjectMap.isEmpty()) {
            map.put("err_code", 1);
            map.put("err_msg", "查询失败");
            map.put("sumGoodNum", sumGoodNum);
            map.put("rows", stringObjectMap);
            map.put("disTotalMoney", totalMoney);
            map.put("totalIntegral", totalIntegral);
        } else {
            map.put("sumGoodNum", sumGoodNum);
            map.put("rows", stringObjectMap);
            map.put("err_code", 0);
            map.put("err_msg", "查询成功");
            map.put("disTotalMoney", totalMoney);
            map.put("totalIntegral", totalIntegral);
        }
        return map;
    }

    @Override
    public Object queryTeacherCommentInfoByQidUid(QuestionComment info) {
        Map<String, Object> map = new HashMap<String, Object>();
        QuestionComment questionComment = questionCommentDao.queryTeacherCommentInfoByQidUid(info);
        if (questionComment != null) {
            map.put("info", questionComment);
            map.put("err_code", 0);
            map.put("err_msg", "查询成功");
        } else {
            map.put("err_code", 1);
            map.put("err_msg", "查询失败");
        }
        return map;
    }


    @Override
    public Object queryDeserveToListen(QuestionComment info) {
        Map<String, Object> map = new HashMap<String, Object>();
        QuestionComment questionComment = questionCommentDao.queryDeserveToListen(info);
        if (questionComment != null) {
            map.put("info", questionComment);
            map.put("err_code", 0);
            map.put("err_msg", "查询成功");
        } else {
            map.put("err_code", 1);
            map.put("err_msg", "查询失败");
        }
        return map;
    }

    @Override
    public Object addCommentNum(Integer id) {
        Map<String, Object> map = new HashMap<String, Object>();
        int row = questionCommentDao.addCommentNum(id);
        if (row > 0) {
            map.put("err_code", 0);
            map.put("err_msg", "新增成功");
        } else {
            map.put("err_code", 1);
            map.put("err_msg", "新增失败");
        }
        return map;
    }

	@Override
	public Object exportExl(QuestionComment info, HttpServletResponse response,HttpSession session){
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
		if(null == loginUser ){
			map.put("err_code", -1);
			map.put("err_msg", "用户未登录");
			return map;
		}
		List<QuestionComment> dataset = questionCommentDao.selectQuestionCommentListPage(info);
		if (dataset == null || dataset.size()==0) {
			map.put("err_code", 404);
			map.put("err_msg", "无可导出数据");
			return map;
		}
		String desc = "";
		String reg = "</?[^<]+>";
		//将问题描述中的html标签过滤掉
		for (QuestionComment questionComment : dataset) {
			if (StringUtils.isNotBlank(questionComment.getCommentContent())) {
				desc = questionComment.getCommentContent().replaceAll(reg, "");
				questionComment.setCommentContent(desc);
			}
		}
		try {
			ExcelUtil.writeExcel(response, "回答"+DateUtil.dateToString(new Date(), DateUtil.FULL_DATE_STR)+".xls", dataset, QuestionComment.class);
			map.put("err_code", 200);
			map.put("err_msg", "导出成功");
		} catch (Exception e) {
			e.printStackTrace();
			map.put("err_code", 500);
			map.put("err_msg", "导出失败");
		}
		return map;
	}

    public void dealListenAuth(QuestionComment comment, List<QuestionCommentDto> list,UserMemberInfo userMemberInfo) {
        //处理语音权限
        ListIterator<QuestionCommentDto> questionCommentListIterator = list.listIterator();
        while (questionCommentListIterator.hasNext()) {
            QuestionCommentDto next = questionCommentListIterator.next();
            if (next.getIsNeedPrivilege() != null && next.getIsNeedPrivilege().equals(1)) {
                //语音提问
                if (next.getCommentTimeOut() != null && next.getCommentTimeOut() == 0) {
                     //免费三小时
                     next.setStatus(0);
                 }
                //导师判断,回答人和当前用户一直就是受益人
                 else if (comment.getGoodUserId() != null && (comment.getGoodUserId().equals(next.getUserId()) || comment.getGoodUserId().equals(next.getCommenterId()))) {
                    next.setStatus(1);
                } else if (userMemberInfo != null) {
                    //免费三小时
                    next.setStatus(4);
                } else if (next.getUbpId() != null) {
                    //用户可以直接收听语音，返回权限通过
                    next.setStatus(2);
                } else {
                    //订单没有支付
                    next.setStatus(3);
                }
            }
        }
    }

    @Override
    public Object queryPageTopicCommentsHot(QuestionComment comment, HttpSession session) {
        Map<String, Object> map = new HashMap<String, Object>();
        //get userId
        UserInfo userInfo = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
//        if (userInfo == null) {
//            map.put("err_code", -1);
//            map.put("err_msg", "当前用户未登录");
//            return map;
//        }
//        Integer id = userInfo.getId();
        comment.setGoodUserId(userInfo==null?null:userInfo.getId());
        UserMemberInfo userMemberInfo = userMemberInfoDao.selectIsVipByUserId(userInfo==null?null:userInfo.getId());
        List<QuestionComment> list1 = questionCommentDao.queryPageTopicCommentsHot(comment);
        ListIterator<QuestionComment> questionCommentListIterator = list1.listIterator();
        while (questionCommentListIterator.hasNext()) {
            QuestionComment next = questionCommentListIterator.next();
            if (next.getIsNeedPrivilege() != null && next.getIsNeedPrivilege().equals(1)) {
                //语音提问
                if (next.getTimeOut() == 0) {
                    //免费三小时
                    next.setStatus(0);
                } else if ((comment.getGoodUserId() != null) && (comment.getGoodUserId().equals(next.getUserId()) || comment.getGoodUserId().equals(next.getCommentedId()))) {
                    next.setStatus(1);//导师判断,回答人和当前用户一直就是受益人
                } else if (null != userMemberInfo) {//会员
                    //用户可以直接收听语音，返回权限通过
                    next.setStatus(4);
                } else if (next.getUbpId() != null) {
                    //用户可以直接收听语音，返回权限通过
                    next.setStatus(2);
                } else {
                    //订单没有支付
                    next.setStatus(3);
                }
            }
        }
        System.out.println("---------------------------------date ---------" + new Timestamp(System.currentTimeMillis()).toString());
        if (null != list1 && list1.size() > 0) {
            map.put("err_code", 0);
            map.put("err_msg", "查询成功");
            map.put("rows", list1);
        } else {
            map.put("err_code", 2);
            map.put("err_msg", "无数据");
            map.put("rows", null);
        }
        return map;
    }

    //积分添加
    private Integer addIntegral(QuestionComment qComment) {
        if (qComment.getQuoteCommentId() != null && qComment.getQuoteCommentId() > 0) {//二级评论，回写一级评论的评论数
            questionCommentDao.addCommentNum(qComment.getQuoteCommentId());

            //评论回答的操作，新增积分
            IntegralInfo integral = IntegralUtil.setIntegral(qComment.getUserId()
                    , IntegralEnum.COMMIT.getScore()
                    , IntegralEnum.COMMIT.getTypeDesc()
                    , IntegralEnum.COMMIT.getTypeId()
                    , qComment.getId());

            //爱值添加
            HappinessInfo hi = HappinessInfoUtil.setHappinessInfo(qComment.getUserId()
                    , HappinessInfoEnum.COMMIT.getLoveValue(), HappinessInfoEnum.COMMIT.getTypeDesc()
                    , HappinessInfoEnum.COMMIT.getTypeId(), "0", qComment.getId());
            happinessInfoDao.insert(hi);
            return integral.getScore();
        } else {//回答
            //增加积分
            IntegralInfo integral = IntegralUtil.setIntegral(qComment.getUserId()
                    , IntegralEnum.ANSWER.getScore()
                    , IntegralEnum.ANSWER.getTypeDesc()
                    , IntegralEnum.ANSWER.getTypeId()
                    , qComment.getId());

            //爱值添加
            HappinessInfo hi = HappinessInfoUtil.setHappinessInfo(qComment.getUserId()
                    , HappinessInfoEnum.ANSWER.getLoveValue(), HappinessInfoEnum.ANSWER.getTypeDesc()
                    , HappinessInfoEnum.ANSWER.getTypeId(), "0", qComment.getId());
            happinessInfoDao.insert(hi);
            return integral.getScore();
        }
    }

	@Override
	public Object drawConsultant(QuestionComment comment, HttpSession session) {
		Map<String, Object> map = new HashMap<String, Object>();
        UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
//        if (userInfo == null) {
//            map.put("err_code", -1);
//            map.put("err_msg", "当前用户未登录");
//            return map;
//        }
        if (StringUtils.isBlank(comment.getSortType())) {
        	map.put("err_code", 400);
        	map.put("err_msg", "参数异常");
        	return map;
		}
        //判断用户是否是会员
        UserMemberInfo userMemberInfo = userMemberInfoDao.selectIsVipByUserId(comment.getUserId());
        /*
         * 顾问-我的
         */
        if (comment.getSortType().equals("mine")) {
			comment.setVipFlag(userMemberInfo==null?0:1);//非会员0 会员1
			comment.setGoodUserId(comment.getUserId());
			List<QuestionComment> list = questionCommentDao.queryConsultantMine(comment);
			ListIterator<QuestionComment> questionCommentListIterator = list.listIterator();
            while (questionCommentListIterator.hasNext()) {
                QuestionComment next = questionCommentListIterator.next();
                Integer isNeedPrivilege = next.getIsNeedPrivilege();
                if (isNeedPrivilege != null && isNeedPrivilege.equals(1)) {
                    //付费提问
                    if (next.getTimeOut() == 0) {
                        //免费三小时
                        next.setStatus(0);
                    } else if ((comment.getGoodUserId() != null) && (comment.getGoodUserId().equals(next.getUserId()) || comment.getGoodUserId().equals(next.getCommentedId()))) {
                        next.setStatus(1);//导师判断,回答人和当前用户一直就是受益人
                    } else if (null != userMemberInfo) {//会员
                        //用户可以直接收听语音，返回权限通过
                        next.setStatus(4);
                    } else if (next.getUbpId() != null) {
                        //用户可以直接收听语音，返回权限通过
                        next.setStatus(2);
                    } else {
                        //订单没有支付
                        next.setStatus(3);
                    }
                }
            }
			if (list != null && list.size()>0) {
				map.put("err_code", 200);
	            map.put("err_msg", "查询成功");
				map.put("rows", list);
			}else {
				map.put("err_code", 200);
	            map.put("err_msg", "查询无数据");
				map.put("rows", list);
			}
		}
        /*
         * 顾问-热门
         */
        else if (comment.getSortType().equals("hot")) {
        	comment.setIsNeedPrivilege(1);//只展示付费问答
        	comment.setGoodUserId(comment.getUserId());
        	List<QuestionComment> list = questionCommentDao.queryPageCommentsHot(comment);
        	
            ListIterator<QuestionComment> questionCommentListIterator = list.listIterator();
            while (questionCommentListIterator.hasNext()) {
                QuestionComment next = questionCommentListIterator.next();
                Integer isNeedPrivilege = next.getIsNeedPrivilege();
                if (isNeedPrivilege != null && isNeedPrivilege.equals(1)) {
                    //付费提问
                    if (next.getTimeOut() == 0) {
                        //免费三小时
                        next.setStatus(0);
                    } else if ((comment.getGoodUserId() != null) && (comment.getGoodUserId().equals(next.getUserId()) || comment.getGoodUserId().equals(next.getCommentedId()))) {
                        next.setStatus(1);//导师判断,回答人和当前用户一直就是受益人
                    } else if (null != userMemberInfo) {//会员
                        //用户可以直接收听语音，返回权限通过
                        next.setStatus(4);
                    } else if (next.getUbpId() != null) {
                        //用户可以直接收听语音，返回权限通过
                        next.setStatus(2);
                    } else {
                        //订单没有支付
                        next.setStatus(3);
                    }
                }
            }
            if (list != null && list.size()>0) {
				map.put("err_code", 200);
	            map.put("err_msg", "查询成功");
				map.put("rows", list);
			}else {
				map.put("err_code", 200);
	            map.put("err_msg", "查询无数据");
				map.put("rows", list);
			}
		}
        
        /*
         * 顾问-最新
         */
        else if (comment.getSortType().equals("new")) {
        	QuestionInfo info = new QuestionInfo();
        	info.setPage(comment.getPage());
        	info.setRows(comment.getRows());
            info.setGoodUserId(comment.getUserId());
            comment.setGoodUserId(comment.getUserId());
            info.setIsPay(2);//付费
            info.setQuestionTime(new Timestamp(System.currentTimeMillis()));
            List<QuestionCommentDto> list = questionInfoDao.queryDynamicPageByInfo(info);
            dealListenAuth(comment, list, userMemberInfo);
            if (list != null && list.size()>0) {
				map.put("err_code", 200);
	            map.put("err_msg", "查询成功");
				map.put("rows", list);
			}else {
				map.put("err_code", 200);
	            map.put("err_msg", "查询无数据");
				map.put("rows", list);
			}
		}
		return map;
	}
	
	@Override
	public Object drawHome(QuestionComment comment, HttpSession session) {
        UserInfo loginUser = (UserInfo) session.getAttribute(GlobalConstant.USER_INFO);
        if (null == loginUser) {
			return ResultUtil.error(ResultEnum.NOT_LOGIN);
		}
        /*
         * 家长大学
         */
//		UserSchoolRel rel = new UserSchoolRel();
//        rel.setUserId(comment.getUserId());
//        rel.setSchoolId(schoolId==null?0:schoolId);
//        UserSchoolRelDTO dto = userSchoolRelDao.queryByUserId(rel);
//
//        //家长大学的未读消息 （红色数字）
//        MessageInfo msg = new MessageInfo();
//        msg.setUserId(comment.getUserId());
//        msg.setVideoTypeId(dto.getVideoTypeId());
//        int totalUnreadNum = questionCommentDao.queryTotalUnReadNumByCommentedId(msg);
//        int totalUnreadGoodNum = questionCommentDao.queryTotalUnreadGoodNumByCommentedId(msg);
//        map.put("schoolNews", totalUnreadGoodNum+totalUnreadNum);
//   	  map.put("school", dto.getStudentCount()==0?null:dto);
   		
   		/*
         * 家园-最新
         */
         if (comment.getSortType().equals("new")) {
        	QuestionInfo info = new QuestionInfo();
        	info.setPage(comment.getPage());
        	info.setRows(comment.getRows());
            info.setGoodUserId(comment.getUserId());
            comment.setGoodUserId(comment.getUserId());
            info.setQuestionTime(new Timestamp(System.currentTimeMillis()));
            info.setIsPay(1);//免费
            List<QuestionCommentDto> list = questionInfoDao.queryDynamicPageByInfo(info);
            return ResultUtil.success(list);
		}
   		return null;
	}
	
    @Override
    public Object quesyNewTextComment(QuestionInfo info) {
        Map<String, Object> map = new HashMap<String, Object>();
        info.setSortType("new");
        List<QuestionCommentDto> list = questionCommentDao.quesyNewTextComment(info);
        if (list != null && list.size() > 0) {
            map.put("err_code", 200);
            map.put("err_msg", "查询成功");
            map.put("rows", list);
        } else {
            map.put("err_code", 200);
            map.put("err_msg", "查询无数据");
            map.put("rows", list);
        }
        return map;
    }

	@Override
	public Object queryFirstCommentNumByQuestionId(Integer questionId) {
		return ResultUtil.success(questionCommentDao.queryFirstCommentNumByQuestionId(questionId));
	}

	@Override
	public Object queryQuesctionContentByTypeIds() {
		Map<String ,Object> map = new HashMap<String, Object>() ;
		//育儿经验传授：'亲子','育儿'
		String[] childcareTypeIds = videoTypeDao.queryIdByTypeName(ConstantsUtil.getProperty("ADVISER_TOPIC.CHILDCARE"));
		NewCommentWithTypesDTO childcareDTO = null;
		if(childcareTypeIds != null && childcareTypeIds.length > 0){
			childcareDTO = questionCommentDao.queryQuesctionContentByTypeIds(childcareTypeIds);
			if(childcareDTO == null ){
				childcareDTO = new NewCommentWithTypesDTO();
			}
			String ccTypeids = Arrays.toString(childcareTypeIds) ;
			childcareDTO.setTypeIds((ccTypeids.substring(1, ccTypeids.length()-1)).replace(" ", ""));
		}
		map.put("childcare", childcareDTO);
		
		//孩子学习指导：'孩子','学习'
		String[] childrenLearningTypeIds = videoTypeDao.queryIdByTypeName(ConstantsUtil.getProperty("ADVISER_TOPIC.CHILDREN_LEARNING"));
		NewCommentWithTypesDTO childrenLearningDTO = null;
		if(childrenLearningTypeIds != null && childrenLearningTypeIds.length>0){
			childrenLearningDTO = questionCommentDao.queryQuesctionContentByTypeIds(childrenLearningTypeIds);
			if(childrenLearningDTO == null ){
				childrenLearningDTO = new NewCommentWithTypesDTO();
			}
			String clTypeids = Arrays.toString(childrenLearningTypeIds) ;
			childrenLearningDTO.setTypeIds( (clTypeids.substring(1, clTypeids.length()-1)).replace(" ", ""));
		}
		map.put("childrenLearning", childrenLearningDTO);
		
		//婚姻情感烦恼：'婚姻','情感'
		String[] marriageLoveTypeIds = videoTypeDao.queryIdByTypeName(ConstantsUtil.getProperty("ADVISER_TOPIC.MARRIAGE_LOVE"));
		NewCommentWithTypesDTO marriageLoveDTO = null;
		if(marriageLoveTypeIds != null && marriageLoveTypeIds.length > 0){
			marriageLoveDTO = questionCommentDao.queryQuesctionContentByTypeIds(marriageLoveTypeIds);
			if(marriageLoveDTO == null ){
				marriageLoveDTO = new NewCommentWithTypesDTO();
			}
			String mlTypeids = Arrays.toString(marriageLoveTypeIds) ;
			marriageLoveDTO.setTypeIds( (mlTypeids.substring(1, mlTypeids.length()-1)).replace(" ", ""));
		}
		map.put("marriageLove", marriageLoveDTO);
		
		//心理健康疏导：'心理健康','情绪管理'
		String[] mentalHealthTypeIds = videoTypeDao.queryIdByTypeName(ConstantsUtil.getProperty("ADVISER_TOPIC.MENTAL_HEALTH"));
		NewCommentWithTypesDTO mentalHealthDTO = null;
		if(mentalHealthTypeIds != null && mentalHealthTypeIds.length > 0){
			mentalHealthDTO = questionCommentDao.queryQuesctionContentByTypeIds(mentalHealthTypeIds);
			if(mentalHealthDTO == null ){
				mentalHealthDTO = new NewCommentWithTypesDTO();
			}
			String mhTypeids = Arrays.toString(mentalHealthTypeIds) ;
			mentalHealthDTO.setTypeIds( (mhTypeids.substring(1, mhTypeids.length()-1)).replace(" ", ""));
		}
		map.put("mentalHealth", mentalHealthDTO);
		
		map.put("err_code", "0");
		map.put("err_msg", "成功");
		return map;
	}

	@Override
	public Object queryPayQuestionComment(PayQuestionCommentParamDTO dto) {
		int total = questionCommentDao.queryCountPayQuestionComment(dto);
		List<PayQuestionCommentDTO> list = questionCommentDao.queryPayQuestionComment(dto) ;
		return ResultUtil.success(list, total);
	}

	@Override
	public Object queryCountPayQuestionComment(PayQuestionCommentParamDTO dto) {
		int count = questionCommentDao.queryCountPayQuestionComment(dto);
		return ResultUtil.success(count);
	}
}
